package com.imyours.webservice.services;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.hibernate.Session;

import com.imyours.model.team.TeamEntity;
import com.imyours.model.user.UserEntity;
import com.imyours.model.util.HibernateUtil;
import com.imyours.webservice.service.Context;
import com.imyours.webservice.service.ContextService;
import com.imyours.webservice.services.annotation.Service;

/**
 * 添加好友 好友 id 分组 id
 * 
 * @author SLevenc
 */
@Service(name = "addFriend")
public class AddFriend extends ContextService {

	public AddFriend(Context context) {
		super(context);
	}

	public void execute() {
		UserEntity user = getUserEntity();
		if (user != null) {
			long uid = Long.parseLong(context.getParameter().get("userId"));
			long teamid = Long.parseLong(context.getParameter().get("teamId"));
			Session se = HibernateUtil.getSessionFactory().openSession();

			TeamEntity teamEntity = (TeamEntity) se.get(TeamEntity.class, teamid);
			if (teamEntity != null) {
				UserEntity userEntity = (UserEntity) se.get(UserEntity.class, uid);
				if (userEntity != null) {
					teamEntity.getUsers().add(userEntity);
					se.beginTransaction();
					se.update(teamEntity);
					se.getTransaction().commit();
					se.close();

					Map<String, String> userMap = null;
					HashMap<String, Object> teamMap = new HashMap<String, Object>();
					teamMap.put("id", teamEntity.getId());
					teamMap.put("name", teamEntity.getName());
					teamMap.put("order", teamEntity.getOrder());
					logger.info("teamName:" + teamEntity.getName());
					List<Map<String, String>> userList = new ArrayList<Map<String, String>>();
					for (UserEntity ue : teamEntity.getUsers()) {
						userMap = new HashMap<String, String>();
						userMap.put("id", "" + ue.getId());
						userMap.put("nickName", ue.getNickname());
						userList.add(userMap);
					}
					teamMap.put("users", userList);
					context.putResult("team", teamMap);
					context.success();
				} else {
					context.fail(4, "no Data");
				}
			} else {
				context.fail(4, "no Data");
			}

		}
	}

}
